package com.xcx.controller.user;


import com.alibaba.fastjson.JSONObject;
import com.xcx.context.BaseContext;
import com.xcx.result.Result;
import com.xcx.service.user.KnowledgeBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xcx/knowledge")
@Slf4j
public class KnowledgeBaseController {

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;


    @PostMapping("/conversation")
    public Result conversation() {
        log.info("创建新的会话{}", BaseContext.getCurrentId());
        String conversation_id = knowledgeBaseService.conversation();
        return Result.success(conversation_id);
    }

    @PostMapping(value = "/chat")
    public Result streamChatResponse(@RequestBody Map<String, String> map) {

        JSONObject jsonObject = knowledgeBaseService.chat(map);
        return Result.success(jsonObject);
        //        OkHttpClient client = new OkHttpClient.Builder().build();

        // 构建请求体
//        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
//        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(mediaType, "{\"app_id\":\"f272239c-cc61-49a1-93e1-c3047c66fc92\",\"query\":\"" + map.get("query") + "\",\"stream\":true,\"conversation_id\":\"" + map.get("conversationId") + "\"}");


        // 构建请求URL


//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .addHeader("Content-Type", mediaType.toString())
//                .addHeader("Authorization", "Bearer bce-v3/ALTAK-HBBnxbemWUgY6uG6f7ITc/7ef2410588e264284848da18362ae145fb20869e")
//                .build();

        // 流式响应式接口
//        Response response = client.newCall(request).execute();
//            try (ResponseBody responseBody = response.body()) {
//                if (responseBody != null) {
//                    try (BufferedReader reader = new BufferedReader(responseBody.charStream())) {
//                        String line;
//                        while ((line = reader.readLine()) != null) {
//                            if ("".equals(line)) continue;
//                            resp.getOutputStream().write(line.getBytes());
//                            resp.getOutputStream().flush();
//                        }
//                    }
//                }
//            }

//        return ResponseEntity.ok()
//                .header("Access-Control-Allow-Origin", "*")
//                .contentType(org.springframework.http.MediaType.TEXT_EVENT_STREAM)
//                .cacheControl(org.springframework.http.CacheControl.noCache())
//                .body(outputStream -> {
//                    try (Response response = client.newCall(request).execute();
//                         ResponseBody responseBody = response.body();
//                         InputStream inputStream = responseBody.byteStream()) {
//                        if (!response.isSuccessful()) {
//                            throw new IOException("Failed to fetch streaming data, HTTP error code: " + response.code());
//                        }
//                        String rawData = "";
//                        byte[] buffer = new byte[1024];
//                        int bytesRead;
//                        while ((bytesRead = inputStream.read(buffer)) != -1) {
//                            String data = new String(buffer, 0, bytesRead);
//                            String[] lines = data.split("\n");
//                            for (String li : lines) {
//                                if (li.startsWith("data: ")) {
//                                    if (rawData != "") {
//                                        outputStream.write(rawData.substring(6).getBytes());
//                                        outputStream.flush();
//                                    }
//                                    rawData = li;
//                                } else {
//                                    rawData = rawData + li;
//                                }
//                            }
//                        }
//                    } catch (IOException e) {
//                        log.error("Error during streaming data: ", e);
//                        outputStream.write(("{" +
//                                "  \"error_code\": 112," +
//                                "  \"error_msg\": \"" + e.getMessage() + "\"" +
//                                "}").getBytes(StandardCharsets.UTF_8));
//                        outputStream.flush();
//                    }
//                });


        // 读取body中的prompt入参
//        InputStreamReader bodyReader = new InputStreamReader(exchange.getRequestBody());
//        BufferedReader br = new BufferedReader(bodyReader);
//        StringBuilder strBuilder = new StringBuilder();
//        String line;
//        while ((line = br.readLine()) != null) {
//            strBuilder.append(line);
//        }
//        br.close();
//        JSONObject body = JSON.parseObject(strBuilder.toString());
//        String prompt = body.getString("prompt");
//
//        // 发起流式请求
//
//        OutputStream outputStream = exchange.getResponseBody();
//        exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");  // 允许跨域
//        exchange.sendResponseHeaders(200, 0);
//        // 流式返回
//        Response response = client.newCall(request).execute();
//        if (response.isSuccessful()) {
//            ResponseBody responseBody = response.body();
//            if (responseBody != null) {
//                InputStream inputStream = responseBody.byteStream();
//                String rawData = "";
//                byte[] buffer = new byte[1024];
//                int bytesRead;
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    String data = new String(buffer, 0, bytesRead);
//                    String[] lines = data.split("\n");
//                    for (String li : lines) {
//                        if (li.startsWith("data: ")) {
//                            if (rawData != "") {
//                                outputStream.write(rawData.substring(6).getBytes());
//                                outputStream.flush();
//                            }
//                            rawData = li;
//                        } else {
//                            rawData = rawData + li;
//                        }
//                    }
//                }
//            }
//        } else {
//            System.out.println("流式请求异常: " + response);
//        }
//        outputStream.close();
//        exchange.close();
    }


    @PostMapping("/getQuestions")
    public Result getQuestions(@RequestBody Map<String, String> map) {
        List<Map<String, Object>> maps = knowledgeBaseService.getQuestions(map);
        return Result.success(maps);
    }

//    @PostMapping("/getDataAndTime")
    public Result getDataAndTime(@RequestBody Map<String, String> map) {
        JSONObject jsonObject = knowledgeBaseService.getDataAndTime(map);
        return Result.success(jsonObject);
    }

}
